package com.example.xiaoxueqixiangmu.jiemian;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.example.xiaoxueqixiangmu.R;
import com.example.xiaoxueqixiangmu.utils.Constant;
import com.example.xiaoxueqixiangmu.utils.NetUtils;

import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class editMycontact extends AppCompatActivity {
    private ListView listView;
    private SimpleAdapter simpleAdapter;
    private List<Map<String,Object>> item1;
    private OkHttpClient client=new OkHttpClient();
    private Button btnSave;
    private ProgressDialog progressDialog;
    private Map<String,Object> map1,map2,map3,map4,map5;
    private static int RESULT_CODE=101;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_mycontact);
        listView=(ListView)findViewById(R.id.editListView);
        btnSave=(Button)findViewById(R.id.btnSave);

        Map<String,Object> contact=(HashMap<String, Object>)getIntent().getSerializableExtra("row");
        item1=new ArrayList<Map<String, Object>>();

        map1=new HashMap<>();
        String name=(String)contact.get("Names");
        map1.put("key1","姓名");
        map1.put("key2",name);
        map1.put("key3",R.drawable.forward_25);
        item1.add(map1);

        map2=new HashMap<>();
        String idType=(String)contact.get("sf");
        map2.put("key1","证件类型");
        map2.put("key2",idType);
        map2.put("key3",R.drawable.forward_25);
        item1.add(map2);

        map3=new HashMap<>();
        String id=(String)contact.get("ids");
        map3.put("key1","证件号码");
        map3.put("key2",id);
        map3.put("key3",R.drawable.forward_25);
        item1.add(map3);

        map4=new HashMap<>();
        String type=(String)contact.get("posts");
        map4.put("key1","乘客类型");
        map4.put("key2",type);
        map4.put("key3",R.drawable.forward_25);
        item1.add(map4);

        map5=new HashMap<>();
        String tel=(String)contact.get("tels");
        map5.put("key1","电话");
        map5.put("key2",tel);
        map5.put("key3",R.drawable.forward_25);
        item1.add(map5);

        simpleAdapter=new SimpleAdapter(this,item1,R.layout.mylist3,new String[]{"key1","key2","key3"},
                new int[]{R.id.message1,R.id.message2,R.id.edit_icon});
        listView.setAdapter(simpleAdapter);

        ActionBar actionBar=getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, final long id) {
                final int myposition=position;
                if (myposition==0){
                    final TextDialog textDialog=new TextDialog(editMycontact.this);
                    textDialog.setIcon(R.mipmap.ic_launcher);
                    textDialog.setTitle("请输入姓名");
                    textDialog.show();

                    View textEntryView = textDialog.getNameDialog();
                    Button name_ok=(Button)textEntryView.findViewById(R.id.name_ok);
                    Button name_cancel=(Button)textEntryView.findViewById(R.id.name_cancel);
                    final EditText  edit_name=(EditText) textEntryView.findViewById(R.id.edit_name);
                    name_ok.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            String name=edit_name.getText().toString().trim();
                            item1.get(myposition).put("key2",name);
                            simpleAdapter.notifyDataSetChanged();
                            textDialog.dismiss();
                        }
                    });
                    name_cancel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            textDialog.dismiss();
                        }
                    });

                }else if (myposition==1){
                    final AlertDialog.Builder builder1=new AlertDialog.Builder(editMycontact.this);
                    builder1.setTitle("请选择证件类型");
                    final String[] items=new String[]{"身份证","学生证","军人证"};
                    final int[] select = {-1};
                    builder1.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            String item1=items[which];
                            select[0] = which;
                            Toast.makeText(getApplicationContext(),"您选择的是"+item1,Toast.LENGTH_SHORT).show();
                        }
                    });
                    builder1.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int i) {
                            Map map=item1.get(1);
                            String content=items[select[0]];
                            map.put("key2",content);
                            item1.set(1,map);
                            Intent intent=new Intent();
                            intent.putExtra("row",(Serializable)item1.get(myposition));
                            simpleAdapter.notifyDataSetChanged();
                        }
                    });
                    builder1.setNegativeButton("取消",null);
                    builder1.create().show();
                }else if (myposition==2){
                    final TextDialog textDialog2=new TextDialog(editMycontact.this);
                    textDialog2.setIcon(R.mipmap.ic_launcher);
                    textDialog2.setTitle("请输入证件号码");
                    textDialog2.show();

                    View textEntryView2 = textDialog2.getNameDialog();
                    final EditText  edt_id=(EditText) textEntryView2.findViewById(R.id.edit_name);
                    Button name_ok2=(Button)textEntryView2.findViewById(R.id.name_ok);
                    Button name_cancel2=(Button)textEntryView2.findViewById(R.id.name_cancel);
                    name_cancel2.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            textDialog2.dismiss();
                        }
                    });
                    name_ok2.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            String id1=edt_id.getText().toString().trim();
                            item1.get(myposition).put("key2",id1);
                            simpleAdapter.notifyDataSetChanged();
                            textDialog2.dismiss();
                        }
                    });
                }else if (myposition==3){
                    AlertDialog.Builder builder2=new AlertDialog.Builder(editMycontact.this);
                    builder2.setTitle("请选择乘客类型");
                    final String[] item2=new String[]{"成人","儿童","学生","其他"};
                    final int[] select1 = {-1};
                    builder2.setSingleChoiceItems(item2, -1, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            String item=item2[which];
                            select1[0]=which;
                            Toast.makeText(getApplicationContext(),"您选择的是"+item,Toast.LENGTH_SHORT).show();
                        }
                    });
                    builder2.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Map map=item1.get(3);
                            String content=item2[select1[0]];
                            map.put("key2",content);
                            item1.set(3,map);
                            Intent intent=new Intent();
                            intent.putExtra("row",(Serializable)item1.get(myposition));
                            simpleAdapter.notifyDataSetChanged();
                        }
                    });
                    builder2.setNegativeButton("取消",null);
                    builder2.create().show();
                }else if (myposition==4){
                    final TextDialog textDialog3=new TextDialog(editMycontact.this);
                    textDialog3.setIcon(R.mipmap.ic_launcher);
                    textDialog3.setTitle("请输入证件号码");
                    textDialog3.show();

                    View textEntryView3 = textDialog3.getNameDialog();
                    final EditText  edt_tel=(EditText) textEntryView3.findViewById(R.id.edit_name);
                    Button name_ok3=(Button)textEntryView3.findViewById(R.id.name_ok);
                    Button name_cancel3=(Button)textEntryView3.findViewById(R.id.name_cancel);
                    name_cancel3.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            textDialog3.dismiss();
                        }
                    });
                    name_ok3.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            String id2=edt_tel.getText().toString().trim();
                            item1.get(myposition).put("key2",id2);
                            simpleAdapter.notifyDataSetChanged();
                            textDialog3.dismiss();
                        }
                    });
                }
            }
        });

        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                if (!NetUtils.check(editMycontact.this)){
                    Toast.makeText(editMycontact.this,"网络异常！",Toast.LENGTH_SHORT).show();
                    return;
                }
                //弹出对话框
                progressDialog=ProgressDialog.show(editMycontact.this,null,"正在加载中...",false,true);

                new Thread(){
                    @Override
                    public void run() {
                        super.run();
                        String result="";

                        SharedPreferences preferences=editMycontact.this.getSharedPreferences("userinfo", Context.MODE_PRIVATE);
                        String value=preferences.getString("cookie","");
                        final String name=item1.get(0).get("key2").toString();
                        final String idType=item1.get(1).get("key2").toString();
                        final String id=item1.get(2).get("key2").toString();
                        final String type=item1.get(3).get("key2").toString();
                        final String tel=item1.get(4).get("key2").toString();
                        try {
                            RequestBody requestBody=new FormBody.Builder()
                                    .add("姓名",name)
                                    .add("证件类型",idType)
                                    .add("证件号码",id)
                                    .add("乘客类型",type)
                                    .add("电话",tel)
                                    .add("action","update")
                                    .build();

                            Request request=new Request.Builder()
                                    .addHeader("Cookie",value)
                                    .url(Constant.Host+"/otn/Passenger")
                                    .post(requestBody)
                                    .build();
                            Response response=client.newCall(request).execute();
                            result=response.body().string();
                            if ("\"1\"".equals(result)){
                                if (progressDialog!=null){
                                    progressDialog.dismiss();
                                }
                                editMycontact.this.finish();
                            }
                        }catch (IOException e){
                            e.printStackTrace();
                        }
                    }
                }.start();
            }
        });
    }

    private void remove(final String name,final String idType,final String id,final String type,final  String tel){
        new Thread(){
            @Override
            public void run() {
                super.run();
                SharedPreferences preferences=editMycontact.this.getSharedPreferences("userinfo", Context.MODE_PRIVATE);
                String value=preferences.getString("cookie","");
                try {
                    RequestBody requestBody=new FormBody.Builder()
                            .add("姓名",name)
                            .add("证件类型",idType)
                            .add("证件号码",id)
                            .add("乘客类型",type)
                            .add("电话",tel)
                            .add("action","remove")
                            .build();

                    Request request=new Request.Builder()
                            .addHeader("Cookie",value)
                            .url(Constant.Host+"/otn/Passenger")
                            .post(requestBody)
                            .build();

                    Response response=client.newCall(request).execute();
                    String result=response.body().string();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }.start();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        try {
            Class<?>menuClass=Class.forName("com.android.internal.view.menu.MenuBuilder");
            Method menuMethod=menuClass.getDeclaredMethod("setOptionalIconsVisible",boolean.class);
            menuMethod.setAccessible(true);
            menuMethod.invoke(menu,true);
        }catch (Exception e){
            e.printStackTrace();
        }
        MenuInflater inflater=getMenuInflater();
        inflater.inflate(R.menu.editcontact_menu,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
            case R.id.delete:
                String name=item1.get(0).get("key2").toString();
                String idType=item1.get(1).get("key2").toString();
                String id=item1.get(2).get("key2").toString();
                String type=item1.get(3).get("key2").toString();
                String tel=item1.get(4).get("key2").toString();
                remove(name,idType,id,type,tel);

//                      RESULT_CODE=100;
//                      setResult(RESULT_CODE);
                editMycontact.this.finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}